<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Middleware;

use Hyperf\Context\Context;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CorsMiddleware implements MiddlewareInterface
{
    public function __construct(protected RequestInterface $request, protected \Hyperf\HttpServer\Contract\ResponseInterface $response)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = Context::get(ResponseInterface::class);
        $response = $response->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Credentials', 'true')
            ->withHeader('Access-Control-Allow-Headers', 'DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization');

        Context::set(ResponseInterface::class, $response);

        $request_id = md5(uniqid((string) time(), true));
        $method = $request->getMethod();
        if ($method == 'GET') {
            $params = $request->getQueryParams();
            $request = $request->withQueryParams(array_merge($params, compact('request_id')));
        } else {
            $params = $request->getParsedBody();
            $request = $request->withParsedBody(array_merge($params, compact('request_id')));
        }

        if ($request->getMethod() == 'OPTIONS' || $request->getUri()->getPath() == '/favicon.ico') {
            return $response;
        }

        return $handler->handle($request);
    }
}
